#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import shutil
import sys

execfile(os.path.join(sys.path[0], "framework.py"))

from oriolus.pith.packets.cryptography import Cryptography
from oriolus.trotter.core import Indexer
from oriolus.trotter.fetchers.persistentfetcher import PersistentFetcher
from test_core import TestCommon
from unittest import TestLoader, TestSuite, TextTestRunner


class TestDownloader(TestCommon):
    def setUp(self):
        TestCommon.setUp(self)

    def tearDown(self):
        TestCommon.tearDown(self)
        
    def test_remote_download_1(self):
        shutil.copy(os.path.abspath("testdata/sourcelist5.yaml"), os.path.abspath(os.path.join(self.work, "sourcelist.yaml")))
        
        crypto = Cryptography(keyring = os.path.abspath("./testdata/test_keyring"))
        crypto.import_public_key(os.path.abspath("./testdata/signed_data/test_oriolus_key.asc"))
        
        indexer = Indexer(self.cache, self.work, PersistentFetcher, verification = True, keyring = os.path.abspath("./testdata/test_keyring"))
        indexer.update()
        self.assertTrue(os.path.exists(os.path.join(self.work, "packetlist.yaml")))
        
        packet_list = indexer.get_packet_list()
        self.assertEqual(["shtrih_keys-1.0.0.0"], packet_list)
        
        indexer.download("shtrih_keys")
        self.assertTrue(os.path.exists(os.path.join(self.work, "shtrih_keys-1.0.0.0.zip.ori")))

    def test_remote_download_2(self):
        shutil.copy(os.path.abspath("testdata/sourcelist5.yaml"), os.path.abspath(os.path.join(self.work, "sourcelist.yaml")))
        
        crypto = Cryptography(keyring = os.path.abspath("./testdata/test_keyring"))
        crypto.import_public_key("./testdata/signed_data/test_oriolus_key.asc")
        
        indexer = Indexer(self.cache, self.work, PersistentFetcher, verification = True, keyring = os.path.abspath("./testdata/test_keyring"))
        indexer.update()
        self.assertTrue(os.path.exists(os.path.join(self.work, "packetlist.yaml")))
        
        packet_list = indexer.get_packet_list()
        self.assertEqual(["shtrih_keys-1.0.0.0"], packet_list)
        
        indexer.download("shtrih_keys")
        self.assertTrue(os.path.exists(os.path.join(self.work, "shtrih_keys-1.0.0.0.zip.ori")))

if __name__ == "__main__":
    suite1 = TestLoader().loadTestsFromTestCase(TestDownloader)
    alltests = TestSuite([suite1])
    TextTestRunner(verbosity=2).run(alltests)